<?php


namespace app\admin\product\model;

use app\common\model\Base;
use app\common\model\member\Member;
use app\common\model\product\money\Type;
use app\common\Player\K3;
use app\common\Player\Kl8;
use app\common\Player\Pc28;
use app\common\Player\Pk10;
use app\common\Player\Pl3;
use app\common\Player\X5;
use app\Request;
use Exception;
use mb\helper\Collection;
use think\facade\Cache;
use think\Db;

class Order
{

    public static $field = [
        'k3' => [
            'sum' => '和值',
            'k33tx' => '三同号通选',
            'k33dx' => '三同号单选',
            'k33th' => '三不同号',
            'k33lh' => '三连号通选',
            'k32fx' => '二同号复选',
            'k32dx' => '二同号单选',
            'k32th' => '二不同号',
        ],
        'pk10' => [
            'position' => '定位胆',
        ],
        'x5' => [
            'q3zxfs' => '前三直选复式',
        ],
        'kl8' => [
            'rx1' => '任选1',
        ],
        'pl3' => [
            'yxdwdfs' => '一星定位胆复式',
        ],
        'pc28' => [
            'position' => '定位球',
            'special' => '特码'
        ]
    ];
    protected static $table = 'product_orders';

    /**
     * @param array $row
     * @return bool|int|string
     */
    public static function add(array $row)
    {
        $newRow = Collection::elements([
            'orderNo',
            'name',
            'expect',
            'memberId',
            'number',
            'money',
            'type',
            'moneyOrder',
            'timeCreated',
            'timeClosed',
            'ghost',
            'field',
            'value',
            'staffId',
            'teamId',
            'orderPoint',
            'isError',
            'continuity',
            'isLong',
        ], $row);
        $newRow['timeCreated'] = time();
        $newRow['timeClosed'] = 0;
        $newRow['status'] = 'created';
        $newRow['isWin'] = 'padding';
        $newRow['moneyOrderWin'] = 0;
        $newRow['existence'] = 1;
        $newRow = Collection::keyStyle($newRow, Collection::NAME_STYLE_C);
        try {
            return Db::table(self::$table)
                ->insertGetId($newRow);
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @param $filter
     * @return array|Error
     */
    public static function fetch($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $row = Db::table(self::$table)
                ->where($where)
                ->find();
            if (!empty($row)) {
                $row['time_created'] *= 1000;
                return Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    /**
     * @param $filter
     * @return bool|Error
     */
    public static function remove($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->delete();
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @param $newState
     * @return bool|Error
     */
    public static function update($filter, $newState,$connect = null)
    {
        $where = self::parseFilters($filter);
        try {
            if (empty($connect)) {
                $connect = Db::connect();
            }
            $offect = $connect->table(self::$table)
                ->where($where)
                ->update($newState);
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @return array
     */
    public static function parseFilters($filter)
    {
        $where = [];
        if (is_array($filter)) {
            if (!empty($filter['id'])) {
                $where[] = ['id', '=', $filter['id']];
            }
            if (!empty($filter['memberId'])) {
                $where[] = ['member_id', '=', $filter['memberId']];
            }
            if (!empty($filter['orderNo'])) {
                $where[] = ['order_no', '=', $filter['orderNo']];
            }
            if (!empty($filter['name']) && !empty($filter['expect'])) {
                $where[] = ['name', '=', $filter['name']];
                $where[] = ['expect', '=', $filter['expect']];
            }
            if (empty($where)) {
                throw error(-10, '参数错误必须指定id');
            }
        } else {
            $where[] = ['id', '=', intval($filter)];
        }
        return $where;
    }

    /**
     * @param array $filters
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array|Error
     */
    public static function search(array $filters, int $pIndex = 0, int $pSize = 10, int &$total = 0,$connect = null)
    {
        $where = self::parseSearchFilters($filters);
        try {
            if(empty($connect)) {
                $connect = Db::connect();
                }
            if (!empty($pIndex)) {
                $total = $connect->table(self::$table)
                    ->where($where)
                    ->count();
            }
            $query = $connect->table(self::$table)
                ->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            if (!empty($filters['order'])) {
                $query->order(['id' => 'desc']);
            }
            $dataSet = $query->select();

            if (!$dataSet->isEmpty()) {
                return $dataSet->map(
                    function ($row) {
                        $row['time_created'] *= 1000;
                        $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                        return $row;
                    }
                )->toArray();
            }
        } catch (Exception $e) {

            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    public static function sumFiled($filters,$filed)
    {
        $where = self::parseSearchFilters($filters);
        try {
            return Db::table(self::$table)->where($where)->sum($filed);
        }catch (Exception $e) {
            return 0;
        }
    }

    public static function countFiled($filters)
    {
        $where = self::parseSearchFilters($filters);
        try {
            return Db::table(self::$table)->where($where)->count();
        }catch (Exception $e) {
            return 0;
        }
    }

    public static function buyOrder($params)
    {
        //判断用户余额是否足够
        $moneyOrder = $params['moneyOrder'];
        $memberInfo = Member::fetch(intval($params['memberId']));
        if ($memberInfo['money'] < $moneyOrder) {
            return error(-21, lang('用户余额不足'));
        }
        //初始化下注配置
        foreach ($params as $newRow) {
            if(is_array($newRow)) {
                $newRow['orderNo'] = Base::getOrderNo();
                $newRow['ghost'] = $memberInfo['ghost'];
                $newRow['staffId'] = $memberInfo['staffId'];
                $newRow['teamId'] = $memberInfo['teamId'];
                $newRow['staffId'] = $memberInfo['staffId'];
                if ($memberInfo['orderPoint'] > 0) {
                    $orderPoint = $memberInfo['orderPoint'];
                }else{
                    $orderPoint = Base::getSysConfig('orderPoint');
                }
                $newRow['orderPoint'] = $orderPoint;
                $newRow['isError'] = round( $memberInfo['money'] / 81,2) > $newRow['moneyOrder'] ? 1 : 0;
                $result = Order::add($newRow);
                if ($result) {
                    $resultMoney = Member::handleMoney($memberInfo['id'], $newRow['moneyOrder'] * -1);
                    if (!is_error($resultMoney)) {
                         $moneyLogRow = [
                        'memberId' => $memberInfo['id'],
                        'memberMoney' =>$memberInfo['money'],
                        'memberGhost' => $memberInfo['ghost'],
                        'targetId' => $newRow['orderNo'],
                        'type' => 'orderAdd',
                        'money' => $newRow['moneyOrder'] * -1,
                        // 'msg' => "订单号：{$newRow['orderNo']} 订单下注"
                        'msg' => "Số đặt hàng：{$newRow['orderNo']} Đặt cược"
                     ];
                    $memberInfo['money'] = $memberInfo['money'] - $newRow['moneyOrder'];
                    Base::addMoneyLog($moneyLogRow);
                    }else{
                        Order::remove(intval($result));
                    }

                }

            }
        }
        //增加会员统计
        $memberState['order_money'] = $memberInfo['orderMoney'] + $moneyOrder;
        $memberState['order_count'] = $memberInfo['orderCount'] + $params['count'];
        $rule = Base::getSysConfig('withdrawalWater');
        $rule = $rule <= 0 ? 100 :$rule;
        $water = $moneyOrder* ($rule / 100);
        if (false) {
//        if ($memberInfo['waterCaijin'] > 0) {

            if ($memberInfo['waterCaijin'] > $moneyOrder) {
                $memberState['water_caijin'] = $memberInfo['waterCaijin'] - $water;
            }else{
                $waterCaijin = $memberInfo['waterCaijin'] - $water;
                $memberState['water_caijin'] = 0;
                $memberState['water'] = $memberInfo['water'] + $waterCaijin;
            }

        }else{
            $memberState['water'] = $memberInfo['water'] + $water ;
        }
        Member::update(intval($memberInfo['id']),$memberState);
        return true;
    }

    public static function buyOrder2($params)
    {
        //判断用户余额是否足够
        $moneyOrder = $params['moneyOrder'];
        $memberInfo = Member::fetch(intval($params['memberId']));
        if ($memberInfo['money'] < $moneyOrder) {
            return error(-21, lang('用户余额不足'));
        }
        Member::handleMoney($memberInfo['id'], $moneyOrder * -1);
        //初始化下注配置
        foreach ($params as $newRow) {
            if(is_array($newRow)) {
                $newRow['orderNo'] = Base::getOrderNo();
                $newRow['ghost'] = $memberInfo['ghost'];
                $newRow['staffId'] = $memberInfo['staffId'];
                $newRow['teamId'] = $memberInfo['teamId'];
                $newRow['staffId'] = $memberInfo['staffId'];
                if ($memberInfo['orderPoint'] > 0) {
                    $orderPoint = $memberInfo['orderPoint'];
                }else{
                    $orderPoint = Base::getSysConfig('orderPoint');
                }
                $newRow['orderPoint'] = $orderPoint;
                Order::add($newRow);
                $moneyLogRow = [
                    'memberId' => $memberInfo['id'],
                    'memberMoney' =>$memberInfo['money'],
                    'memberGhost' => $memberInfo['ghost'],
                    'targetId' => $newRow['orderNo'],
                    'type' => 'orderAdd',
                    'money' => $moneyOrder * -1,
                    // 'msg' => "订单号：{$newRow['orderNo']} 订单下注"
                    'msg' => "Số đặt hàng：{$newRow['orderNo']} Đặt cược"
                ];
                Base::addMoneyLog($moneyLogRow);
                //增加会员统计
//                $orderPoint = 0;
//                if ($memberInfo['orderPoint'] > 0) {
//                    $orderPoint = $memberInfo['orderPoint'];
//                }else{
//                    $orderPoint = Base::getSysConfig('orderPoint');
//                }
//                $memberState = [];
//                if ($orderPoint > 0 ) {
//                    $memberState['order_point'] = $moneyOrder * ($orderPoint / 100);
//                }
                $memberState['order_money'] = $memberInfo['orderMoney'] + $moneyOrder;
                $memberState['order_count'] = $memberInfo['orderCount'] + 1;
                Member::update(intval($memberInfo['id']),$memberState);
                //总流水
            }
        }
        return true;
    }
    public function groupOrder()
    {

    }

    public static function parseSearchFilters($filters)
    {
        $where = [];
        if (!empty($filters['memberId'])) {
            $where[] = ['member_id', '=', $filters['memberId']];
        }
        if (!empty($filters['memberIds'])) {
            $where[] = ['member_id', 'in', $filters['memberIds']];
        }
        if (!empty($filters['existence'])) {
            $where[] = ['existence', '=', $filters['existence']];
        }
        if (!empty($filters['status'])) {
            $where[] = ['status', '=', $filters['status']];
        }
        if (!empty($filters['field'])) {
            $where[] = ['field', '=', $filters['field']];
        }
        if (isset($filters['value'])) {
            $where[] = ['value', '=', $filters['value']];
        }
        if (isset($filters['isLong'])) {
            $where[] = ['is_long', '=', $filters['isLong']];
        }
        if (!empty($filters['isWin'])) {
            $where[] = ['is_win', '=', $filters['isWin']];
        }
        if (!empty($filters['name'])) {
            $where[] = ['name', '=', $filters['name']];
        }
        if (!empty($filters['expect'])) {
            $where[] = ['expect', '=', $filters['expect']];
        }
        if (!empty($filters['staffId'])) {
            $where[] = ['staff_id', '=', $filters['staffId']];
        }
        if (!empty($filters['teamId'])) {
            $where[] = ['team_id', '=', $filters['teamId']];
        }
        if (!empty($filters['orderNo'])) {
            $where[] = ['order_no', '=', $filters['orderNo']];
        }
        if (!empty($filters['timeCreatedStart'])) {
            $where[] = ['time_created', '>=', $filters['timeCreatedStart']];
        }
        if (!empty($filters['timeCreatedEnd'])) {
            $where[] = ['time_created', '<=', $filters['timeCreatedEnd']];
        }
        if (isset($filters['ghost'])) {
            $where[] = ['ghost', '=', $filters['ghost']];
        }
        if (!empty($filters['noPadding'])) {
            $where[] = ['is_win', 'in', ['win','lose']];
        }
        if (isset($filters['isWater'])) {
            $where[] = ['is_water', '=', $filters['isWater']];
        }
        if (isset($filters['isError'])) {
            $where[] = ['is_error', '=', $filters['isError']];
        }
        if (isset($filters['field'])) {
            $where[] = ['field', '=', $filters['field']];
        }
//        var_dump($where);
//        if (!empty($filters['order'])) {
//            $where['order'] = $filters['order'];
//        }
        return $where;
    }
}
